package com.ljy.my_study.java.juc.lock.readwritelock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTestMain {

    public static void main(String[] args) {
        Point point=new Point();
        Runnable runnable=()->{
            point.move(1,2);
        };
        new Thread(runnable).start();
        System.out.println("distance:"+point.distanceFromOrigin());
        try {
            Thread.sleep(100L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("distance:"+point.distanceFromOrigin());
    }

    static class Point{
        private int x,y;
        private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();

        public void move(double dX,double dY){
            try{
                lock.writeLock().lock();
                System.out.println("move start");
                x+=dX;
                y+=dY;
                try {
                    Thread.sleep(3000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("move end");
            }finally {
                lock.writeLock().unlock();
            }
        }

        public double distanceFromOrigin(){
            try{
                lock.readLock().lock();
                double currentX=x,currentY=y;
                double result=Math.sqrt(currentX*currentX+currentY+currentY);
                return result;
            }finally {
                lock.readLock().unlock();
            }
        }
    }
}
